package com.yeskery.nut.cloud.registry.nacos;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.yeskery.nut.annotation.bean.Bean;
import com.yeskery.nut.annotation.bean.Configuration;
import com.yeskery.nut.annotation.condition.ConditionalOnMissingBean;
import com.yeskery.nut.annotation.condition.ConditionalOnWebApplicationType;
import com.yeskery.nut.core.Environment;

import java.util.Optional;

/**
 * nacos服务注册注册器
 * @author YESKERY
 * 2024/1/12
 */
@Configuration
public class NacosServerRegistryRegistrar {

    /**
     * 配置nacos服务注册bean
     * @return nacos服务注册bean
     */
    @Bean
    @ConditionalOnWebApplicationType
    public NacosServerRegistry nacosServerRegistry() {
        return new NacosServerRegistry();
    }

    /**
     * 配置nacos服务
     * @param environment 环境对象
     * @return nacos服务对象
     * @throws NacosException Nacos创建异常
     */
    @Bean
    @ConditionalOnMissingBean(NamingService.class)
    @ConditionalOnWebApplicationType
    public NamingService nacosServerNamingService(Environment environment) throws NacosException {
        String serverAddr = Optional.ofNullable(environment.getEnvProperty("nut.cloud.registry.nacos.serverAddr")).orElse("127.0.0.1:8848");
        return NamingFactory.createNamingService(serverAddr);
    }
}
